<?php

namespace App\Extensions;

use Encore\Admin\Actions\RowAction;

class LinkRowAction extends RowAction
{
    protected $href;
    protected $target;
    protected $data;

    public function __construct($href, $name = '', $target = '_blank')
    {
        if (is_array($href)) {
            $this->data = $href;
        } else {
            $this->data = [[$href, $name, $target]];
        }
        $this->target = $target;
        parent::__construct();
    }

    public function name(): string
    {
        return <<<HTML
    &nbsp;{$this->name}
HTML;
    }

    public function __toString()
    {
        return $this->render();
    }

    public function render(): string
    {
        $res = collect($this->data)->map(function ($item) {
            return sprintf('<a href="%s" target="%s">%s</a>',
                $item[0],
                $item[2] ?? $this->target,
                $item[1] ?? ''
            );
        })->implode('&nbsp;');
        return sprintf('<span style="white-space:nowrap;">%s</span>', $res);
    }

}
